package com.taocore.top.title.servlet;

import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.taocore.top.title.service.RealTimeDataJob;
import com.taocore.top.title.service.Top5wDataJob;

public class MainServlet extends HttpServlet{

	static Logger _log = Logger.getLogger(MainServlet.class.getName());
	
	public static String JOB_KEY_TOP_5W = "top5w";
	public static String JOB_KEY_REALTIME = "realtime";
	
	private static String root;
	
	public void init()
	{
		root = getServletContext().getRealPath("/");
		try {
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			scheduler.start();
//			startTop5wDataSchedulelr();
			startRealTimeDataSchedulelr();
		} catch (SchedulerException e) {
			_log.log(Level.SEVERE, "", e);
		} catch (ParseException e) {
			_log.log(Level.SEVERE, "", e);
		}
	}
	
	private void startTop5wDataSchedulelr() throws SchedulerException, ParseException
	{
		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
		if (!scheduler.checkExists(new JobKey(JOB_KEY_TOP_5W)))
		{
			JobDetail job = JobBuilder.newJob(Top5wDataJob.class)
	        .withIdentity(JOB_KEY_TOP_5W)
	        .build();
	
			Trigger trigger = TriggerBuilder.newTrigger()
	            .withIdentity(JOB_KEY_TOP_5W)
	            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 14 * * 3"))            
	            .build();
	        
	        scheduler.scheduleJob(job, trigger);
		}
	}
	
	private void startRealTimeDataSchedulelr() throws SchedulerException, ParseException
	{
		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
		if (!scheduler.checkExists(new JobKey(JOB_KEY_REALTIME)))
		{
			JobDetail job = JobBuilder.newJob(RealTimeDataJob.class)
	        .withIdentity(JOB_KEY_REALTIME)
	        .build();
	
			Trigger trigger = TriggerBuilder.newTrigger()
	            .withIdentity(JOB_KEY_REALTIME)
	            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 * * ?"))            
	            .build();
	        
	        scheduler.scheduleJob(job, trigger);
		}
	}
	
	public void destroy()
	{
		try {
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			scheduler.shutdown();
		} catch (SchedulerException e) {
			_log.log(Level.SEVERE, "", e);
		}
	}
	
	public static String getRootPath()
	{
		return root;
	}
}
